//
//  PillowDeviceInfoViewController.m
//  Lightthings
//
//  Created by 王岩 on 2025/1/9.
//

#import "PillowDeviceInfoViewController.h"
#import "DeviceInfoModel.h"
#import "DeviceFouncModel.h"
#import "HomeItemModel.h"
#import "PillowTimeSetModel.h"
#import "LevelSetModel.h"
@interface PillowDeviceInfoViewController ()
<FRQBluetoothManagerDelegate>
/* <#note#> */

@property (nonatomic, strong) DeviceInfoModel * deviceInfo;
@property (nonatomic, strong) BaseModel * switchModel;
@property (nonatomic, strong) LevelSetModel * levelSetModel;
@property (nonatomic, strong) PillowTimeSetModel * timeSetModel;
@property (nonatomic, strong) HomeItemModel * xinlv, *huxilv, *qingxing, *zhihan, *dahan,  *tidong, *qianshui,  *shenshui;

/* <#note#> */
@property (nonatomic, strong) NSMutableArray * xinlvList, *huxilvList, *tidongList, *dahanList,  *zhihanList, *qingxingList, *shenshuiList, *qianshuiList;
@end

@implementation PillowDeviceInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.jy_title = @"止鼾枕";
    self.collectionInsets = kEdge(self.jy_bar_h, 0, 0, 0);
    
    [self.rightBtn setTitle:SWString(@"断开") forState:0];
    self.rightBtn.zh_action = kMsgForward(@"closeAction", WKProxy(self));
    
    NSString * uuid = self.metaInfo[@"uuid"];
    NSArray * list = [FRQBluetoothManager shareManager].curPeripherals;
    for (CBPeripheral * per in list) {
        if ([per.identifier.UUIDString isEqualToString:uuid]) {
            self.peripheral = per;
        }
    }
    
    MainSectionModel * s = [[MainSectionModel alloc] init];
    [s sectionInsets:kEdge(0, 20, 20, 20) ls:10 is:10];
    
    DeviceInfoModel * info = [[DeviceInfoModel alloc] init];
    info.per = self.peripheral;
    [s.items addObject:info];
    _deviceInfo = info;
    
    _huxilv = [HomeItemModel cModelWithBgImage:@"1 拷贝" Title:SWString(@"呼吸率") Value:[self defaultValueString:@"0" Unit:SWString(@"次/分")] SmallImg:@"呼吸率"];
    [s.items addObject:_huxilv];
    
    _xinlv = [HomeItemModel cModelWithBgImage:@"2 拷贝" Title:SWString(@"心率") Value:[self defaultValueString:@"0" Unit:@"bmp"] SmallImg:@"心率"];
    [s.items addObject:_xinlv];
    
    
    _dahan = [HomeItemModel cModelWithBgImage:@"3 拷贝" Title:SWString(@"打鼾次数") Value:[self defaultValueString:@"0" Unit:SWString(@"次")] SmallImg:@"打鼾 1"];
    [s.items addObject:_dahan];
    
    _tidong = [HomeItemModel cModelWithBgImage:@"4 拷贝" Title:SWString(@"体动次数") Value:[self defaultValueString:@"0" Unit:SWString(@"次")] SmallImg:@"体动"];
    [s.items addObject:_tidong];
    
    _qingxing = [HomeItemModel cModelWithBgImage:@"1 拷贝" Title:SWString(@"清醒时长") Value:[self defaultValueString:@"0" Unit:SWString(@"分")] SmallImg:@"清醒"];
    [s.items addObject:_qingxing];
    
    _qianshui = [HomeItemModel cModelWithBgImage:@"2 拷贝" Title:SWString(@"浅睡时长") Value:[self defaultValueString:@"0" Unit:SWString(@"分")] SmallImg:@"浅睡-43"];
    [s.items addObject:_qianshui];
    
    _shenshui = [HomeItemModel cModelWithBgImage:@"3 拷贝" Title:SWString(@"深睡时长") Value:[self defaultValueString:@"0" Unit:SWString(@"分")] SmallImg:@"深睡"];
    [s.items addObject:_qianshui];
    
    _zhihan = [HomeItemModel cModelWithBgImage:@"4 拷贝" Title:SWString(@"止鼾次数") Value:[self defaultValueString:@"0" Unit:SWString(@"次")] SmallImg:@"止鼾"];
    [s.items addObject:_zhihan];
    
    MainSectionModel * s2 = [[MainSectionModel alloc] init];

    
    NormalArrowModel * jiankong = [NormalArrowModel createTitle:SWString(@"睡眠监控") size:CGSizeMake(kScreenWidth, 50) hiddenArrow:NO action:kRunCMDINFO(@"show_PillowSleepDetectionView", @{@"uuid":self.metaInfo[@"uuid"]})];
    jiankong.icon = @"睡眠监控-46";
    [s2.items addObject:jiankong];
    
    [s2.items addObject:space_ff(20)];
    
    NormalArrowModel * set = [NormalArrowModel createTitle:SWString(@"设置") size:CGSizeMake(kScreenWidth, 50) hiddenArrow:NO action:kRunCMDINFO(@"show_PillowSetView", @{@"uuid":self.metaInfo[@"uuid"]})];
    set.icon = @"设置";
    [s2.items addObject:set];
    
    [s2.items addObject:space_ff(20)];

    
    self.dataSources = @[s, s2];
    
    self.xinlvList = [NSMutableArray new];
    self.huxilvList = [NSMutableArray new];
    self.tidongList = [NSMutableArray new];
    self.dahanList = [NSMutableArray new];
    self.zhihanList = [NSMutableArray new];
    self.qingxingList = [NSMutableArray new];
    self.shenshuiList = [NSMutableArray new];
    self.qianshuiList = [NSMutableArray new];
    
    [self readBaseDataInfo];
    // Do any additional setup after loading the view.
}

//- (void)viewDidAppear:(BOOL)animated {
//    [super viewDidAppear:animated];
//    [PillowCommandTool.sharedInstance updateDateAndTimeCallBack:^(NSString * data) {
//
//    } RealTimeData:NO StopSwith:NO ToPeripheral:self.peripheral];
//}

- (NSMutableAttributedString *)defaultValueString:(NSString *)value Unit:(NSString *)unit {
    return [SWTool attS1:value s2:[NSString stringWithFormat:@"  %@",unit] f1:U_bfont(22) c1:KLColor(@"ffffff") f2:U_font(14) c2:KLColor(@"ffffff")];
}
- (NormalArrowModel *)cModelWithTitle:(NSString *)title Image:(NSString *)icon {
    NormalArrowModel * m = [NormalArrowModel createTitle:title size:CGSizeMake(kScreenWidth - 40, 55) hiddenArrow:NO];
    m.idfBlock = ^NSString * _Nonnull{
        return @"BleControlFunctionCell";
    };
    m.icon = icon;
    return m;
}

- (void)readBaseDataInfo {
   
    [PillowCommandTool.sharedInstance SynchronousDataCallBack:^(NSString * _Nonnull data) {
        if (data) {
            if ([[data substringWithRange:NSMakeRange(4, 2)] isEqualToString:@"a3"]) {
                [self calculatePIN个JunData:data];
            }
            if ([[data substringWithRange:NSMakeRange(4, 2)] isEqualToString:@"a2"]) {
                [self calculatePIN个JunData:data];
                NSString * sort = [data substringWithRange:NSMakeRange(8, 4)];
                long a = strtoll([[NSString stringWithFormat:@"0x%@",sort] UTF8String], 0, 16);
                NSMutableArray * dataArray = [NSMutableArray array];
                unsigned char byte3 = (a & 0xff00)>>8;
                unsigned char byte4 = (a & 0xff);
                [dataArray addObject:@(byte3)];
                [dataArray addObject:@(byte4)];
                [dataArray addObject:@(1)];
                [self getNextDataWithArray:dataArray];
            }
        }
    } ToPeripheral:self.peripheral];
    
}

- (void)getNextDataWithArray:(NSArray *)dataArray {
    [PillowCommandTool.sharedInstance SynchronousDataRespondValue:dataArray CallBack:^(NSString * _Nonnull data) {
        if ([[data substringWithRange:NSMakeRange(4, 2)] isEqualToString:@"a3"] || [[data substringWithRange:NSMakeRange(4, 2)] isEqualToString:@"a2"]) {
            [self calculatePIN个JunData:data];
        }
        NSMutableArray * dataArray = [NSMutableArray array];
        NSString * sort = [data substringWithRange:NSMakeRange(8, 4)];
        long a = strtoll([[NSString stringWithFormat:@"0x%@",sort] UTF8String], 0, 16);
        [dataArray removeAllObjects];
        unsigned char byte3 = (a & 0xff00)>>8;
        unsigned char byte4 = (a & 0xff);
        [dataArray addObject:@(byte3)];
        [dataArray addObject:@(byte4)];
        [dataArray addObject:@(1)];
        [self getNextDataWithArray:dataArray];
    } ToPeripheral:self.peripheral];
}

- (void)calculatePIN个JunData:(NSString *)data {
    
    if ([[data substringWithRange:NSMakeRange(4, 2)] isEqualToString:@"a3"]){
        int xinlv = 0;
        for (NSNumber * num in self.xinlvList) {
            xinlv = xinlv + num.intValue;
        }
        xinlv = xinlv / self.xinlvList.count;
        self.xinlv.value = [self defaultValueString:[NSString stringWithFormat:@"%d", xinlv] Unit:@"bmp"];
        
        int huxi = 0;
        for (NSNumber * num in self.huxilvList) {
            huxi = huxi + num.intValue;
        }
        huxi = huxi / self.huxilvList.count;
        self.huxilv.value = [self defaultValueString:[NSString stringWithFormat:@"%d", huxi] Unit:SWString(@"次/分")];
        
        int tidong = 0;
        for (NSNumber * num in self.tidongList) {
            tidong = tidong + num.intValue;
        }
        self.tidong.value = [self defaultValueString:[NSString stringWithFormat:@"%d", tidong] Unit:SWString(@"次")];
        
        int dahan = 0;
        for (NSNumber * num in self.dahanList) {
            dahan = dahan + num.intValue;
        }
        self.dahan.value = [self defaultValueString:[NSString stringWithFormat:@"%d", dahan] Unit:SWString(@"次")];
        
        int zhihan = 0;
        for (NSNumber * num in self.zhihanList) {
            zhihan = zhihan + num.intValue;
        }
        self.zhihan.value = [self defaultValueString:[NSString stringWithFormat:@"%d", zhihan] Unit:SWString(@"次")];
        
        self.qingxing.value = [self defaultValueString:[NSString stringWithFormat:@"%ld",self.qingxingList.count * 2] Unit:SWString(@"分")];
        self.qianshui.value = [self defaultValueString:[NSString stringWithFormat:@"%ld",self.qianshuiList.count * 2] Unit:SWString(@"分")];
        self.shenshui.value = [self defaultValueString:[NSString stringWithFormat:@"%ld",self.shenshuiList.count * 2] Unit:SWString(@"分")];
        
        [self reloadIfNeeded];
        return;
    }
    
    NSString * date = [data substringWithRange:NSMakeRange(12, 8)];
    NSString * time = [data substringWithRange:NSMakeRange(20, 4)];

    long dateValue = strtoll([[NSString stringWithFormat:@"0x%@",date] UTF8String], 0, 16);
    
    NSString * dateStr = [MBDateManager shortDateFromString:[NSString stringWithFormat:@"%ld",dateValue * 1000] style:@"yyyy-MM-dd"];
    
    long timeValue = strtoll([[NSString stringWithFormat:@"0x%@",time] UTF8String], 0, 16);

    NSString * sleepdata = [data substringFromIndex:24];
    sleepdata  = [sleepdata substringToIndex:sleepdata.length - 4];
    NSUInteger a = sleepdata.length / 8;
    
    for (int i = 0; i < a ; i ++) {
        NSString *  one = [sleepdata substringWithRange:NSMakeRange(i * 8, 8)];
        NSString * heart = [one substringWithRange:NSMakeRange(0, 2)];
        long heartValue = strtoll([[NSString stringWithFormat:@"0x%@",heart] UTF8String], 0, 16);
        if (heartValue > 0) {
            [self.xinlvList addObject:@(heartValue)];
        }
        
        NSString * second = [one substringWithRange:NSMakeRange(2, 2)];
        long secondValue = strtoll([[NSString stringWithFormat:@"0x%@",second] UTF8String], 0, 16);
        
        long sleepStatus = secondValue & 0xc0;
        if (sleepStatus == 1) {
            [self.qingxingList addObject:@(sleepStatus)];
        }else if (sleepStatus == 2) {
            [self.qianshuiList addObject:@(sleepStatus)];
        }else if (sleepStatus == 3) {
            [self.shenshuiList addObject:@(sleepStatus)];
        }
        
        long Breath = secondValue & 0x3f;
        if (Breath > 0) {
            [self.huxilvList addObject:@(Breath)];
        }
        
        NSString * Third = [one substringWithRange:NSMakeRange(4, 2)];
        long ThirdValue = strtoll([[NSString stringWithFormat:@"0x%@",Third] UTF8String], 0, 16);
        
        long StopSnoring = ThirdValue & 0x80;
        if (StopSnoring > 0) {
            [self.zhihanList addObject:@(StopSnoring)];
        }
        
        long StopSnoringTimes = ThirdValue & 0x7f;
        if (StopSnoringTimes > 0) {
            [self.dahanList addObject:@(StopSnoringTimes)];
        }
        
        NSString * forth = [one substringWithRange:NSMakeRange(6, 2)];
        long forthValue = strtoll([[NSString stringWithFormat:@"0x%@",forth] UTF8String], 0, 16);
        
        long openStatus = forthValue & 0x80;
        long kinesiaTimes = forthValue & 0x7f;
        if (kinesiaTimes > 0) {
            [self.tidongList addObject:@(kinesiaTimes)];
        }
    }
}



// MARK:   🔥🔥🔥🔥🔥🔥🔥  🔥🔥🔥🔥🔥🔥🔥
- (void)closeAction {
    [FRQBluetoothManager.shareManager closeAuotReconnectPeripheral:self.peripheral];
}
-(void)onBLEManagerDisconnect:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    [self back];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[FRQBluetoothManager shareManager] removeBleDelegate:self];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [FRQBluetoothManager.shareManager addBleDelegate:self];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
